'use strict';

const { isObject } = require('@mly-cli/utils')
const pkgDir = require('pkg-dir').sync
const path = require('path')
const formatPath = require('@mly-cli/format-path')
const { getDefaultRegistry } = require('@mly-cli/get-npm-info')
const npminstall = require('npminstall')

class Package {
  constructor(options) {
    if (!options || !isObject(options) ) {
      throw new Error('Package类的options参数不能为空!')
    }
    this.targetPath = options.targetPath
    this.storePath = options.storePath
    this.storeDir = options.storeDir
    this.packageName = options.packageName
    this.packageVersion = options.packageVersion

  }

  exists() {

  }

  install() {
    return npminstall({
      root: this.targetPath,
      storeDir: this.storeDir,
      register: getDefaultRegistry(),
      pkgs: [
        { 
          name: this.packageName,
          version: this.packageVersion
        }
      ]
    })
  }

  update() {}

  getRootFilePath() {
    const dir = pkgDir(this.targetPath)
    if (dir) {
      const pkgFile = require(path.resolve(dir, 'package.json'))
      if (pkgFile && (pkgFile.main)) {
        return formatPath(path.resolve(dir, pkgFile.main))
      }
    }
    return null
  }
}

module.exports = Package;

